package com.hxkcloud.nurse.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Paint;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;


/**
 * @package: com.huatek.api.utils
 * @ClassName: Utils
 * @Description: 工具集合
 * @author: aaron_han
 * @data: 2015-1-26 下午6:22:13
 */
public class Utils {
	private static final int UNCONSTRAINED = -1;


	//日期转时间戳
	public static String date2TimeStamp(String date_str,String format){
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			return String.valueOf(sdf.parse(date_str).getTime());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	// 时间戳转日期
	public static String timeStamp2Date(String seconds,String format) {
		if(seconds == null || seconds.isEmpty() || seconds.equals("null")){
			return "";
		}
		if(format == null || format.isEmpty()) format = "yyyy-MM-dd HH:mm:ss";
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(new Date(Long.valueOf(seconds)));
	}

	public static void tvTextDeleteLineStyle(TextView tv) {
		tv.getPaint().setFlags(
				Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);// 并加清晰
		tv.getPaint().setAntiAlias(true);// 抗锯齿
	}

	/**
	 * 
	 * @param pic
	 *            原字符串
	 * @param str1
	 *            插入的字符串
	 * @return
	 */
	public static String getInsert(String pic, String str1) {
		StringBuffer s1 = new StringBuffer(pic); // 原字符串
		String hh = s1.substring(s1.lastIndexOf("."));
		System.out.println("ppp==" + hh);
		Pattern p = Pattern.compile(hh); // 插入位置
		Matcher m = p.matcher(s1.toString());

		if (m.find()) {
			s1.insert((m.start() + 0), str1); // 插入字符串

		}
		return s1.toString();
	}

	// 将list等分
	public static <T> List<List<T>> splitList(List<T> list, int pageSize) {
		int listSize = list.size(); // list的大小
		int page = (listSize + (pageSize - 1)) / pageSize; // 页数
		List<List<T>> listArray = new ArrayList<List<T>>(); // 创建list数组
		for (int i = 0; i < page; i++) { // 按照数组大小遍历
			List<T> subList = new ArrayList<T>(); // 数组每一位放入一个分割后的list
			for (int j = 0; j < listSize; j++) { // 遍历待分割的list
				int pageIndex = ((j + 1) + (pageSize - 1)) / pageSize; // 当前记录的页码(第几页)
				if (pageIndex == (i + 1)) { // 当前记录的页码等于要放入的页码时
					subList.add(list.get(j)); // 放入list中的元素到分割后的list(subList)
				}

				if ((j + 1) == ((j + 1) * pageSize)) { // 当放满一页时退出当前循环
					break;
				}
			}
			listArray.add(subList); // 将分割后的list放入对应的数组的位中
		}
		return listArray;
	}

	public static boolean copyApkFromAssets(Context context, String fileName,
			String path) {
		boolean copyIsFinish = false;
		InputStream is = null;
		FileOutputStream fos = null;
		try {
			is = context.getAssets().open(fileName);
			File file = new File(path);
			file.createNewFile();
			fos = new FileOutputStream(file);
			byte[] temp = new byte[1024];
			int i = 0;
			while ((i = is.read(temp)) > 0) {
				fos.write(temp, 0, i);
			}
			copyIsFinish = true;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fos != null) {
					fos.close();
				}
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return copyIsFinish;
	}

	/**
	 * 
	 * @Title:
	 * @Description: 对象转换为字节
	 * @param: @param obj
	 * @param: @return
	 * @return: byte[]
	 * @throws
	 */
	public static byte[] jserialize(Object obj) {
		ObjectOutputStream oos = null;
		ByteArrayOutputStream baos = null;
		try {
			baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			oos.writeObject(obj);
			return baos.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (oos != null)
				try {
					oos.close();
					baos.close();
				} catch (IOException e) {
				}
		}
		return null;
	}

	/**
	 * 
	 * @Title:
	 * @Description: 字节转换为对象
	 * @param: @param bits
	 * @param: @return
	 * @return: Object
	 * @throws
	 */
	public static Object jdeserialize(byte[] bits) {
		ObjectInputStream ois = null;
		ByteArrayInputStream bais = null;
		try {
			bais = new ByteArrayInputStream(bits);
			ois = new ObjectInputStream(bais);
			return ois.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ois != null)
				try {
					ois.close();
					bais.close();
				} catch (IOException e) {
				}
		}
		return null;
	}

	/**
	 * 
	 * @Title:
	 * @Description: 对象转字符串
	 * @param: @param obj
	 * @param: @return
	 * @return: String
	 * @throws
	 */
	public static String object2String(Object obj) {
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		ObjectOutputStream objectOutputStream = null;
		String str = null;
		try {
			objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
			objectOutputStream.writeObject(obj);
			str = new String(Base64.encode(byteArrayOutputStream.toByteArray(),
					Base64.DEFAULT));
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (objectOutputStream != null) {
					objectOutputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return str;
	}

	/**
	 * 
	 * @Title:
	 * @Description: 字符串转对象
	 * @param: @param str
	 * @param: @return
	 * @return: Object
	 * @throws
	 */
	public static Object string2Object(String str) {
		byte[] mobileBytes = Base64.decode(str.getBytes(), Base64.DEFAULT);
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
				mobileBytes);
		ObjectInputStream objectInputStream = null;
		Object obj = null;
		try {
			objectInputStream = new ObjectInputStream(byteArrayInputStream);
			obj = objectInputStream.readObject();
		} catch (StreamCorruptedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				if (objectInputStream != null) {
					objectInputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				byteArrayInputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return obj;
	}

	 public static String utc2Local(String utcTime, String utcTimePatten,
			   String localTimePatten) {
			  SimpleDateFormat utcFormater = new SimpleDateFormat(utcTimePatten);
			  utcFormater.setTimeZone(TimeZone.getTimeZone("UTC"));
			  Date gpsUTCDate = null;
			  try {
			   gpsUTCDate = utcFormater.parse(utcTime);
			  } catch (ParseException e) {
			   e.printStackTrace();
			  }
			  SimpleDateFormat localFormater = new SimpleDateFormat(localTimePatten);
			  localFormater.setTimeZone(TimeZone.getDefault());
			  String localTime = localFormater.format(gpsUTCDate.getTime());
			  return localTime;
			 }

	/**
	 * @Description: 日期转换为时间戳
	 * @param Date
	 * @return
	 */
	public static long getTimeMillisFromDate(String Date) {

		if (TextUtils.isEmpty(Date)) {
			return System.currentTimeMillis();
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		Date date = null;
		try {
			date = sdf.parse(Date);
			return date.getTime();
		} catch (ParseException e) {
			e.printStackTrace();
			return 0;
		}

	}

	/**
	 * @Description: 日期转换为时间戳
	 * @param Date
	 * @return
	 */
	public static long getTimeMillis1FromDate(String Date) {

		if (TextUtils.isEmpty(Date)) {
			return System.currentTimeMillis();
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

		Date date = null;
		try {
			date = sdf.parse(Date);
			return date.getTime();
		} catch (ParseException e) {
			e.printStackTrace();
			return 0;
		}

	}

	/**
	 * 
	 * @Title:
	 * @Description: 分钟 小时倒计时
	 * @param: @param currentTimeMillis
	 * @param: @param itemtime
	 * @param: @return
	 * @return: String
	 * @throws
	 */
	@SuppressLint("SimpleDateFormat")
	public static String showTime(long currentTimeMillis, long itemtime) {
		long time = currentTimeMillis / 1000 - itemtime / 1000;
		if (time < 60 && time >= 0) {
			return "刚刚";
		} else if (time >= 60 && time < 3600) {
			return time / 60 + "分钟前";
		} else if (time >= 3600 && time < 3600 * 24) {
			return time / 3600 + "小时前";
		} else if (time >= 3600 * 24 && time < 3600 * 24 * 30) {
			return time / 3600 / 24 + "天前";
		} else if (time >= 3600 * 24 * 30 && time < 3600 * 24 * 30 * 12) {
			return time / 3600 / 24 / 30 + "个月前";
		} else if (time >= 3600 * 24 * 30 * 12) {
			return time / 3600 / 24 / 30 / 12 + "年前";
		} else {
			return "刚刚";
		}
	}

	/*
	 * 将一个时间戳转换成提示性时间字符串，如刚刚，1秒前
	 * 
	 * @param timeStamp
	 * 
	 * @return
	 */
	public static String convertTimeToFormat(long timeStamp) {
		long curTime = System.currentTimeMillis() / (long) 1000;
		long time = curTime - timeStamp;

		if (time < 60 && time >= 0) {
			return "刚刚";
		} else if (time >= 60 && time < 3600) {
			return time / 60 + "分钟前";
		} else if (time >= 3600 && time < 3600 * 24) {
			return time / 3600 + "小时前";
		} else if (time >= 3600 * 24 && time < 3600 * 24 * 30) {
			return time / 3600 / 24 + "天前";
		} else if (time >= 3600 * 24 * 30 && time < 3600 * 24 * 30 * 12) {
			return time / 3600 / 24 / 30 + "个月前";
		} else if (time >= 3600 * 24 * 30 * 12) {
			return time / 3600 / 24 / 30 / 12 + "年前";
		} else {
			return "刚刚";
		}
	}

	/**
	 * 秒转化为小时分钟
	 */
	public static String ssToHHmmss(int s) {
		int N = s / 3600;
		s = s % 3600;
		int K = s / 60;
		s = s % 60;
		int M = s;
		if (N == 0 && K != 0) {
			return K + "分钟 " + M + "秒";
		} else if (N == 0 && K == 0) {
			return M + "秒";
		} else {
			return N + "小时 " + K + "分钟 " + M + "秒";
		}
	}

	/**
	 * 获取当前时间并格式化为指定样式
	 */
	@SuppressLint("SimpleDateFormat")
	public static String formatCurrentDate(String format) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		Date curDate = new Date(System.currentTimeMillis());
		return sdf.format(curDate);
	}

	/**
	 * @Description: 隐藏输入法
	 * @param act
	 * @param view
	 * @return: void
	 */
	public static void hideSoftInputFromWindow(Activity act, View view) {
		InputMethodManager imm = (InputMethodManager) act
				.getApplicationContext().getSystemService(
						Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
	}

	public static void hideSoftInputFromWindow(Activity act) {
		View view = act.getCurrentFocus();
		if (view != null)
			((InputMethodManager) act
					.getSystemService(Context.INPUT_METHOD_SERVICE))
					.hideSoftInputFromWindow(view.getWindowToken(), 0);
	}

	// 隐藏输入发
	public static void hideSoftInputFromWindow(Context context) {
		View view = ((Activity) context).getWindow().peekDecorView();
		if (view != null && view.getWindowToken() != null) {
			InputMethodManager imm = (InputMethodManager) context
					.getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
		}
	}

	public static void hideSoftInputFromWindow(Context context, View view) {
		InputMethodManager imm = (InputMethodManager) context
				.getApplicationContext().getSystemService(
						Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
	}

	/**
	 * 保留一位小数
	 */
	public static String decimalFormatNoe(float scale) {
		DecimalFormat fnum = new DecimalFormat("##0.0");
		return fnum.format(scale);
	}

	// 读取pcm文件
	public static byte[] getPCMData(String filePath) {
		File file = new File(filePath);
		FileInputStream inStream;
		try {
			inStream = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}

		byte[] data_pack = null;
		if (inStream != null) {
			long size = file.length();

			data_pack = new byte[(int) size];
			try {
				inStream.read(data_pack);
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			} finally {
				try {
					inStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return data_pack;
	}

	public static short[] byteArray2ShortArray(byte[] b) {
		int len = b.length / 2;
		int index = 0;
		short[] re = new short[len];
		byte[] buf = new byte[2];
		for (int i = 0; i < b.length;) {
			buf[0] = b[i];
			buf[1] = b[i + 1];
			short st = byteToShort(buf);
			re[index] = st;
			index++;
			i += 2;
		}
		return re;
	}

	public static short byteToShort(byte[] b) {
		short s = 0;
		short s0 = (short) (b[0] & 0xff);// 最低位
		short s1 = (short) (b[1] & 0xff);
		s1 <<= 8;
		s = (short) (s0 | s1);
		return s;
	}

	/**
	 * 
	 * @Title:
	 * @Description:浏览网页
	 * @param: @param act
	 * @param: @param phone
	 * @return: void
	 * @throws
	 */
	public static void browseWebpage(Activity act, String url) {
		if (TextUtils.isEmpty(url)) {
			return;
		}
		Intent intent = new Intent();
		intent.setAction("android.intent.action.VIEW");
		Uri content_url = Uri.parse(url);
		intent.setData(content_url);
		act.startActivity(intent);
	}

	/**
	 * 
	 * @Title:
	 * @Description:发送短信
	 * @param: @param act
	 * @param: @param phone
	 * @return: void
	 * @throws
	 */
	public static void sendMsg(Activity act, String phone) {
		Uri uri = Uri.parse("smsto:".concat(phone));
		Intent it = new Intent(Intent.ACTION_SENDTO, uri);
		// it.putExtra("sms_body", "102");
		act.startActivity(it);
	}

	/**
	 * 
	 * @Title:
	 * @Description: 滚动聚焦
	 * @param: @param view
	 * @return: void
	 * @throws
	 */
	public static void getFocusable(View view) {
		view.setFocusable(true);
		view.setFocusableInTouchMode(true);
		view.requestFocus();
	}

	/**
	 * 
	 * @Title:
	 * @Description: 格式化
	 * @param: @param context
	 * @param: @param res
	 * @param: @param obj
	 * @param: @return
	 * @return: String
	 * @throws
	 */
	public static String getFormatString(Context context, int res,
			Object... obj) {
		return String.format(context.getString(res), obj);
	}

	/**
	 * @Description:
	 * @param options
	 * @param minSideLength
	 * @param maxNumOfPixels
	 * @return 动态计算出图片的inSampleSize
	 * @return: int
	 */
	public static int computeSampleSize(Options options,
			int minSideLength, int maxNumOfPixels) {
		int initialSize = computeInitialSampleSize(options, minSideLength,
				maxNumOfPixels);
		int roundedSize;
		if (initialSize <= 8) {
			roundedSize = 1;
			while (roundedSize < initialSize) {
				roundedSize <<= 1;
			}
		} else {
			roundedSize = (initialSize + 7) / 8 * 8;
		}
		return roundedSize;
	}

	private static int computeInitialSampleSize(Options options,
			int minSideLength, int maxNumOfPixels) {
		double w = options.outWidth;
		double h = options.outHeight;
		// Math.ceil(Math.sqrt(w * h / maxNumOfPixels)) ：w * h /
		// maxNumOfPixels平方结果的小数部分一律向整数部分进位
		int lowerBound = (maxNumOfPixels == UNCONSTRAINED) ? 1 : (int) Math
				.ceil(Math.sqrt(w * h / maxNumOfPixels));
		// Math.floor(w / minSideLength) 将w / minSideLength结果值一律舍去小数，仅保留整数
		int upperBound = (minSideLength == UNCONSTRAINED) ? 128 : (int) Math
				.min(Math.floor(w / minSideLength),
						Math.floor(h / minSideLength));
		if (upperBound < lowerBound) {
			return lowerBound;
		}
		if ((maxNumOfPixels == UNCONSTRAINED)
				&& (minSideLength == UNCONSTRAINED)) {
			return 1;
		} else if (minSideLength == UNCONSTRAINED) {
			return lowerBound;
		} else {
			return upperBound;
		}
	}

	public static final Bitmap resizeBitmap(Bitmap bitmap, int maxSize) {
		int srcWidth = bitmap.getWidth();
		int srcHeight = bitmap.getHeight();
		int width = maxSize;
		int height = maxSize;
		boolean needsResize = false;
		if (srcWidth > srcHeight) {
			if (srcWidth > maxSize) {
				needsResize = true;
				height = ((maxSize * srcHeight) / srcWidth);
			}
		} else {
			if (srcHeight > maxSize) {
				needsResize = true;
				width = ((maxSize * srcWidth) / srcHeight);
			}
		}
		if (needsResize) {
			Bitmap retVal = Bitmap.createScaledBitmap(bitmap, width, height,
					true);
			return retVal;
		} else {
			return bitmap;
		}
	}

	public static Bitmap doImageBitmap(InputStream in) {
		Bitmap bitmap = null;
		Options options = null;
		final int BUFFER_SIZE = 2048;
		if (in == null) {
			return null;
		}
		try {
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			byte[] bytes = new byte[BUFFER_SIZE];
			int len = -1;
			while ((len = in.read(bytes)) != -1) {
				outStream.write(bytes, 0, len);
				outStream.flush();
			}
			byte[] data = new byte[outStream.toByteArray().length];
			data = outStream.toByteArray();
			outStream.close();
			in.close();
			options = new Options();
			// 这里设置true的时候，decode时候Bitmap返回的为空， 将图片宽高读取放在Options里.
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeByteArray(data, 0, data.length, options);
			// 计算浏览列表显示图片的缩放比例值
			options.inSampleSize = Utils.computeSampleSize(options, -1,
					(400 * 400) * 2);
			options.inJustDecodeBounds = false;
			bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,
					options);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return recycleBitmap(bitmap);
	}

	public static Bitmap recycleBitmap(Bitmap bitmap) {
		if (bitmap == null) {
			return bitmap;
		}
		Bitmap newBitmap = bitmap.copy(Config.ARGB_8888, false);
		if (newBitmap != bitmap) {
			bitmap.recycle();
		}
		return newBitmap;
	}

	// public static Bitmap createBitmap(Bitmap bitmap, Context context) {
	// Bitmap watermark = BitmapFactory.decodeResource(context.getResources(),
	// R.drawable.add_water_mark);
	// int w = bitmap.getWidth();
	// int h = bitmap.getHeight();
	// int ww = watermark.getWidth();
	// int wh = watermark.getHeight();
	// Bitmap newb = Bitmap.createBitmap(w, h, Config.ARGB_8888);
	// // 创建一个新的和SRC长度宽度一样的位图
	// Canvas canvas = new Canvas(newb);
	// canvas.drawBitmap(bitmap, 0, 0, null);// 在 0，0坐标开始画入bitmap
	// canvas.drawBitmap(watermark, w - ww, h - wh, null);// 在bitmap的右下角画入水印
	// canvas.save(Canvas.ALL_SAVE_FLAG);
	// canvas.restore();
	// watermark.recycle();
	// return newb;
	// }


	// public static Bitmap watermarkBitmap(Bitmap bitmap, String title, Context
	// context, Options options, boolean isFlag) {
	// if (bitmap == null) {
	// return null;
	// }
	// Bitmap watermark = BitmapFactory.decodeResource(context.getResources(),
	// R.drawable.add_water_mark, options);
	// int w = bitmap.getWidth();
	// int h = bitmap.getHeight();
	// // 需要处理图片太大造成的内存超过的问题,这里我的图片很小所以不写相应代码了
	// Bitmap newb = Bitmap.createBitmap(w, h, Config.ARGB_8888);//
	// 创建一个新的和SRC长度宽度一样的位图
	// Canvas cv = new Canvas(newb);
	// cv.drawBitmap(bitmap, 0, 0, null);// 在 0，0坐标开始画入src
	// int ww = watermark.getWidth();
	// int wh = watermark.getHeight();
	// // 加入图片
	// if (watermark != null) {
	// cv.drawBitmap(watermark, w - ww + 5, h - wh + 5, null);// 在src的右下角画入水印
	// }
	// // 加入文字
	// if (title != null) {
	// String familyName = "宋体";
	// Typeface font = Typeface.create(familyName, Typeface.BOLD);
	// TextPaint textPaint = new TextPaint();
	// textPaint.setColor(Color.RED);
	// textPaint.setTypeface(font);
	// textPaint.setAlpha(50);
	// if (isFlag) {
	// textPaint.setTextSize(25);
	// cv.drawText(title, w - ww / 2, h - 30, textPaint);
	// } else {
	// textPaint.setTextSize(18);
	// cv.drawText(title, 40, h - 50, textPaint);
	// }
	// }
	// cv.save(Canvas.ALL_SAVE_FLAG);// 保存
	// cv.restore();// 存储
	// watermark.recycle();
	// bitmap.recycle();
	// return recycleBitmap(newb);
	// }

	public static boolean isRoot() {
		try {
			Process process = Runtime.getRuntime().exec("su");
			process.getOutputStream().write("exit\n".getBytes());
			process.getOutputStream().flush();
			int i = process.waitFor();
			if (0 == i) {
				process = Runtime.getRuntime().exec("su");
				return true;
			}
		} catch (Exception e) {
			return false;
		}
		return false;

	}

	/**
	 * 返回当前程序屏幕分辨率信息
	 */
	public static DisplayMetrics getDisplayMetrics(Context context) {
		DisplayMetrics dm = new DisplayMetrics();
		((Activity) context).getWindowManager().getDefaultDisplay()
				.getMetrics(dm);
		return dm;
	}

	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dip2px(float dpValue, Context context) {
		float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 */
	public static int px2dip(float pxValue, Context context) {
		float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	/**
	 * 将sp值转换为px值，保证文字大小不变
	 * 
	 */
	public static int sp2px(Context context, float spValue) {
		final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
		return (int) (spValue * fontScale + 0.5f);
	}

	/**
	 * 将px值转换为sp值，保证文字大小不变
	 */
	public static int px2sp(Context context, float pxValue) {
		final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
		return (int) (pxValue / fontScale + 0.5f);
	}

	/**
	 * 获得状态栏的高度
	 */
	public static int getStatusHeight(Context context) {

		int statusHeight = -1;
		try {
			Class clazz = Class.forName("com.android.internal.R$dimen");
			Object object = clazz.newInstance();
			int height = Integer.parseInt(clazz.getField("status_bar_height")
					.get(object).toString());
			statusHeight = context.getResources().getDimensionPixelSize(height);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return statusHeight;
	}

	/**
	 * 计算Listview高度
	 */
	public static void setListViewHeightBasedOnChildren(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}
		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();

		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
	}

	/**
	 * 判断给定字符串是否空白串。 空白串是指由空格、制表符、回车符、换行符组成的字符串 若输入字符串为null或空字符串，返回true
	 * 
	 * @param input
	 * @return boolean
	 */
	public static boolean isEmpty(String input) {
		if (input == null || "".equals(input) || "null".equals(input))
			return true;

		for (int i = 0; i < input.length(); i++) {
			char c = input.charAt(i);
			if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
				return false;
			}
		}
		return true;
	}
}
